package com.zzh.lib.recorder.whole.record;

import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zzh.lib.recorder.HRecorder;
import com.zzh.lib.recorder.R;
import com.zzh.lib.recorder.base.activity.BaseActivity;
import com.zzh.lib.recorder.base.pop.PopupManager;
import com.zzh.lib.recorder.base.utils.FileUtils;
import com.zzh.lib.recorder.base.utils.StaticFinalValues;
import com.zzh.lib.recorder.whole.createVideoByVoice.localEdit.LocalVideoActivity;
import com.zzh.lib.recorder.whole.pickvideo.beans.VideoFile;
import com.zzh.lib.recorder.whole.record.beans.MediaObject;
import com.zzh.lib.recorder.whole.record.beans.RecordUIParams;
import com.zzh.lib.recorder.whole.record.other.MagicFilterType;
import com.zzh.lib.recorder.whole.record.ui.CameraView;
import com.zzh.lib.recorder.whole.record.ui.CustomRecordImageView;
import com.zzh.lib.recorder.whole.record.ui.FocusImageView;
import com.zzh.lib.recorder.whole.record.ui.ProgressView;
import com.zzh.lib.recorder.whole.record.ui.SlideGpuFilterGroup;
import com.zzh.lib.recorder.whole.videoPlayer.VideoPlayerActivity2;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.zzh.lib.recorder.base.utils.StaticFinalValues.CHANGE_IMAGE;
import static com.zzh.lib.recorder.base.utils.StaticFinalValues.DELAY_DETAL;
import static com.zzh.lib.recorder.base.utils.StaticFinalValues.OVER_CLICK;
import static com.zzh.lib.recorder.base.utils.StaticFinalValues.RECORD_MIN_TIME;

public class RecorderActivity extends BaseActivity implements View.OnTouchListener, SlideGpuFilterGroup.OnFilterChangeListener {
    private static final int VIDEO_MAX_TIME = 30 * 1000;
    CameraView mRecordCameraView;
    ProgressView mVideoRecordProgressView;
    LinearLayout mMatchingBack;
    Button mVideoRecordFinishIv;
    ImageView mMeetCamera;
    LinearLayout mIndexDelete;
    TextView mIndexAlbum;
    CustomRecordImageView mCustomRecordImageView;
    FrameLayout mRecordBtnLl;
    ImageView mVideoFilter;
    FocusImageView mRecorderFocusIv;
    ImageView mCountTimeDownIv;
    public int mNum = 0;
    private long mLastTime = 0;
    public float mRecordTimeInterval;
    ExecutorService executorService;
    private MediaObject mMediaObject;
    private RecordUIParams mRecordUIParams;
    View tv_use_video;

    private MyHandler mMyHandler = new MyHandler(this);
    private boolean isRecording = false;

    @Override
    protected int setLayoutId() {
        return R.layout.h_lib_act_recorder;
    }


    @Override
    protected void onResume() {
        super.onResume();
        mVideoRecordProgressView.setData(mMediaObject);
    }

    @Override
    public void initView() {
        mRecordUIParams = getIntent().getParcelableExtra("data");
        if (mRecordUIParams == null) {
            mRecordUIParams = new RecordUIParams();
            String cacheDir = getCacheDir().getAbsolutePath();
            mRecordUIParams.setFileVideoSavePath(cacheDir + "/video/");
        } else {
            if (TextUtils.isEmpty(mRecordUIParams.fileVideoSavePath)) {
                String cacheDir = getCacheDir().getAbsolutePath();
                mRecordUIParams.setFileVideoSavePath(cacheDir + "/video/");
            }
        }
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        androidx.appcompat.app.ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.hide();
        }
        mRecordCameraView = findViewById(R.id.record_camera_view);
        tv_use_video = findViewById(R.id.tv_use_video);
        mVideoRecordProgressView = findViewById(R.id.video_record_progress_view);
        mMatchingBack = findViewById(R.id.matching_back);
        mVideoRecordFinishIv = findViewById(R.id.video_record_finish_iv);
        mMeetCamera = findViewById(R.id.switch_camera);
        mIndexDelete = findViewById(R.id.index_delete);
        mIndexAlbum = findViewById(R.id.index_album);
        mCustomRecordImageView = findViewById(R.id.custom_record_image_view);
        mRecordBtnLl = findViewById(R.id.record_btn_ll);
        mRecorderFocusIv = findViewById(R.id.recorder_focus_iv);
        mVideoFilter = findViewById(R.id.video_filter);
        mCountTimeDownIv = findViewById(R.id.count_time_down_iv);
        mRecordBtnLl = findViewById(R.id.record_btn_ll);
        if (mMediaObject == null) {
            mMediaObject = new MediaObject();
        }
        executorService = Executors.newSingleThreadExecutor();
        mRecordCameraView.setOnTouchListener(this);
        mRecordCameraView.setOnFilterChangeListener(this);
        mVideoRecordProgressView.setMaxDuration(VIDEO_MAX_TIME, false);
        mVideoRecordProgressView.setOverTimeClickListener(new ProgressView.OverTimeClickListener() {
            @Override
            public void overTime() {
                mCustomRecordImageView.performClick();
            }

            @Override
            public void noEnoughTime() {
                setBackAlpha(mVideoRecordFinishIv, 255);
            }

            @Override
            public void isArriveCountDown() {
                mCustomRecordImageView.performClick();
            }
        });
        setBackAlpha(mVideoRecordFinishIv, 127);


        ///
        mMatchingBack.setOnClickListener(this::onViewClicked);
        mMeetCamera.setOnClickListener(this::onViewClicked);
        mVideoRecordFinishIv.setOnClickListener(this::onViewClicked);
        mIndexDelete.setOnClickListener(this::onViewClicked);
        mIndexAlbum.setOnClickListener(this::onViewClicked);
        mCustomRecordImageView.setOnClickListener(this::onViewClicked);
        mVideoFilter.setOnClickListener(this::onViewClicked);
        tv_use_video.setOnClickListener(this::onViewClicked);
        mVideoRecordFinishIv.setVisibility(mRecordUIParams.showNext ? View.VISIBLE : View.GONE);
        mIndexAlbum.setVisibility(mRecordUIParams.showLocalVideo ? View.VISIBLE : View.GONE);
        mVideoFilter.setVisibility(mRecordUIParams.showBeautyFilter ? View.VISIBLE : View.GONE);
    }

    public void onViewClicked(View view) {
        if (System.currentTimeMillis() - mLastTime < 500) {
            return;
        }
        mLastTime = System.currentTimeMillis();
        if (view.getId() != R.id.index_delete) {
            if (mMediaObject != null) {
                MediaObject.MediaPart part = mMediaObject.getCurrentPart();
                if (part != null) {
                    if (part.remove) {
                        part.remove = false;
                        if (mVideoRecordProgressView != null)
                            mVideoRecordProgressView.invalidate();
                    }
                }
            }
        }
        int id = view.getId();
        if (id == R.id.matching_back) {
            onBackPressed();
        } else if (id == R.id.video_record_finish_iv) {
            onStopRecording();
            if (mMediaObject != null) {
                videoFileName = mMediaObject.mergeVideo();
            }
            VideoPlayerActivity2.launch(RecorderActivity.this, videoFileName);

        } else if (id == R.id.switch_camera) {
            try {
                mRecordCameraView.switchCamera();
                mRecordCameraView.changeBeautyLevel(0);
            } catch (Exception ex) {

            }
        } else if (id == R.id.index_delete) {
            MediaObject.MediaPart part = mMediaObject.getCurrentPart();
            if (part != null) {
                if (part.remove) {
                    part.remove = false;
                    mMediaObject.removePart(part, true);
                    if (mMediaObject.getMedaParts().size() == 0) {
                        mIndexDelete.setVisibility(View.GONE);
                        mIndexAlbum.setVisibility(View.VISIBLE);
                    }
                    if (mMediaObject.getDuration() < RECORD_MIN_TIME) {
                        setBackAlpha(mVideoRecordFinishIv, 127);
                        mVideoRecordProgressView.setShowEnouchTime(false);
                    }
                } else {
                    part.remove = true;
                }
            }
        } else if (id == R.id.custom_record_image_view) {
            if (!isRecording) {
                onStartRecording();
            } else {
                onStopRecording();
            }
        } else if (id == R.id.video_filter) {
            if (mRecordCameraView.getCameraId() == 0) {
                Toast.makeText(this, "后置摄像头 不使用美白磨皮功能", Toast.LENGTH_SHORT).show();
                return;
            }
            hideOtherView();
            new PopupManager(this).showBeautyLevel(mRecordCameraView.getBeautyLevel(), new PopupManager.SelBeautyLevel() {
                @Override
                public void selBeautyLevel(int level) {
                    showOtherView();
                    mRecordCameraView.changeBeautyLevel(level);
                }
            });
        } else if (id == R.id.tv_use_video) {
            Intent intent = new Intent();
            intent.putExtra("videoPath", mRecordUIParams.fileVideoSavePath);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private void onStartRecording() {
        isRecording = true;
        String storageMp4;
        if (mRecordUIParams.fileVideoSavePath.endsWith(".mp4")) {
            storageMp4 = mRecordUIParams.fileVideoSavePath;
        } else {
            storageMp4 = FileUtils.getVideoCacheDir(mRecordUIParams.fileVideoSavePath, String.valueOf(System.currentTimeMillis()));
        }
        Log.d("----start video---", storageMp4);
        mRecordUIParams.setFileVideoSavePath(storageMp4);
        mMediaObject.buildMediaPart(storageMp4);
        mRecordCameraView.setSavePath(storageMp4);
        mRecordCameraView.startRecord();
        mCustomRecordImageView.startRecord();
        mVideoRecordProgressView.start();
        alterStatus();
    }

    private void onStopRecording() {
        isRecording = false;
        mRecordCameraView.stopRecord();
        mVideoRecordProgressView.stop();
        //录制释放有延时，稍后处理
        mMyHandler.sendEmptyMessageDelayed(DELAY_DETAL, 250);
        mCustomRecordImageView.stopRecord();
        alterStatus();
    }

    private void setBackAlpha(Button view, int alpha) {
        if (alpha > 127) {
            view.setClickable(true);
        } else {
            view.setClickable(false);
        }
        view.getBackground().setAlpha(alpha);
    }

    private void showOtherView() {
        if (mMediaObject != null && mMediaObject.getMedaParts().size() == 0) {
            mIndexDelete.setVisibility(View.GONE);
            mIndexAlbum.setVisibility(View.VISIBLE);
        } else {
            mIndexDelete.setVisibility(View.VISIBLE);
            mIndexAlbum.setVisibility(View.GONE);
        }
        mVideoFilter.setVisibility(View.VISIBLE);
        mMatchingBack.setVisibility(View.VISIBLE);
        mCustomRecordImageView.setVisibility(View.VISIBLE);

        mVideoRecordFinishIv.setVisibility(mRecordUIParams.showNext ? View.VISIBLE : View.GONE);
        mIndexAlbum.setVisibility(mRecordUIParams.showLocalVideo ? View.VISIBLE : View.GONE);
        mVideoFilter.setVisibility(mRecordUIParams.showBeautyFilter ? View.VISIBLE : View.GONE);
    }

    private void hideOtherView() {
        mIndexAlbum.setVisibility(View.INVISIBLE);
        mIndexDelete.setVisibility(View.INVISIBLE);
        mVideoFilter.setVisibility(View.INVISIBLE);
        mMatchingBack.setVisibility(View.INVISIBLE);
        mCustomRecordImageView.setVisibility(View.INVISIBLE);
    }

    //正在录制中
    public void alterStatus() {
        if (isRecording) {
            mIndexAlbum.setVisibility(View.GONE);
            mIndexDelete.setVisibility(View.INVISIBLE);
            mVideoFilter.setVisibility(View.INVISIBLE);
            mMatchingBack.setVisibility(View.INVISIBLE);
            tv_use_video.setVisibility(View.INVISIBLE);
        } else {
            if (mMediaObject != null && mMediaObject.getMedaParts().size() == 0) {
                mIndexDelete.setVisibility(View.GONE);
            } else {
                mIndexDelete.setVisibility(View.VISIBLE);
            }
            tv_use_video.setVisibility(View.VISIBLE);
            mMatchingBack.setVisibility(View.VISIBLE);
            mMeetCamera.setVisibility(View.VISIBLE);
            mVideoRecordFinishIv.setVisibility(View.VISIBLE);
            mVideoRecordProgressView.setVisibility(View.VISIBLE);
            mVideoRecordFinishIv.setVisibility(mRecordUIParams.showNext ? View.VISIBLE : View.GONE);
            mIndexAlbum.setVisibility(mRecordUIParams.showLocalVideo ? View.VISIBLE : View.GONE);
            mVideoFilter.setVisibility(mRecordUIParams.showBeautyFilter ? View.VISIBLE : View.GONE);
            mMeetCamera.setVisibility(mRecordUIParams.showSwitchCamera ? View.VISIBLE : View.GONE);
        }

    }

    private void hideAllView() {
        hideOtherView();
        mVideoRecordFinishIv.setVisibility(View.GONE);
        mVideoRecordProgressView.setVisibility(View.GONE);
        mMeetCamera.setVisibility(View.GONE);
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mRecordCameraView.onTouch(event);
        if (mRecordCameraView.getCameraId() == 1) {
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                float sRawX = event.getRawX();
                float sRawY = event.getRawY();
                float rawY = sRawY * HRecorder.screenWidth / HRecorder.screenHeight;
                float temp = sRawX;
                float rawX = rawY;
                rawY = (HRecorder.screenWidth - temp) * HRecorder.screenHeight / HRecorder.screenWidth;

                Point point = new Point((int) rawX, (int) rawY);
                mRecordCameraView.onFocus(point, new Camera.AutoFocusCallback() {
                    @Override
                    public void onAutoFocus(boolean success, Camera camera) {
                        if (success) {
                            mRecorderFocusIv.onFocusSuccess();
                        } else {
                            mRecorderFocusIv.onFocusFailed();
                        }
                    }
                });
                mRecorderFocusIv.startFocus(new Point((int) sRawX, (int) sRawY));
        }
        return true;
    }

    @Override
    public void onFilterChange(final MagicFilterType type) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (type == MagicFilterType.NONE) {
                    Toast.makeText(RecorderActivity.this, "当前没有设置滤镜--" + type, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(RecorderActivity.this, "当前滤镜切换为--" + type, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    private static class MyHandler extends Handler {

        private WeakReference<RecorderActivity> mVideoRecordActivity;

        public MyHandler(RecorderActivity videoRecordActivity) {
            mVideoRecordActivity = new WeakReference<>(videoRecordActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            RecorderActivity activity = mVideoRecordActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case DELAY_DETAL:
                        activity.mMediaObject.stopRecord(activity, activity.mMediaObject);
                        break;
                    case CHANGE_IMAGE:
                        switch (activity.mNum) {
                            case 0:
                                activity.mCountTimeDownIv.setVisibility(View.VISIBLE);
                                activity.mCountTimeDownIv.setImageResource(R.drawable.bigicon_3);
                                activity.mMyHandler.sendEmptyMessageDelayed(CHANGE_IMAGE, 1000);
                                break;
                            case 1:
                                activity.mCountTimeDownIv.setImageResource(R.drawable.bigicon_2);
                                activity.mMyHandler.sendEmptyMessageDelayed(CHANGE_IMAGE, 1000);
                                break;
                            case 2:
                                activity.mCountTimeDownIv.setImageResource(R.drawable.bigicon_1);
                                activity.mMyHandler.sendEmptyMessageDelayed(CHANGE_IMAGE, 1000);
                                break;
                            default:
                                activity.mMyHandler.removeCallbacks(null);
                                activity.mCountTimeDownIv.setVisibility(View.GONE);
                                activity.mVideoRecordProgressView.setVisibility(View.VISIBLE);
                                activity.mCustomRecordImageView.setVisibility(View.VISIBLE);
                                activity.mCustomRecordImageView.performClick();
                                activity.mVideoRecordProgressView.setCountDownTime(activity.mRecordTimeInterval);
                                break;
                        }
                        if (activity.mNum >= 3) {
                            activity.mNum = 0;
                        } else {
                            activity.mNum++;
                        }
                        break;
                    case OVER_CLICK:
                        activity.mCustomRecordImageView.performClick(); //定时结束
                        break;
                }
            }
        }
    }

    private static final String TAG = "RecorderActivity";

    String videoFileName;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case StaticFinalValues.REQUEST_CODE_PICK_VIDEO:
                if (resultCode == RESULT_OK) {
                    ArrayList<VideoFile> list = data.getParcelableArrayListExtra(StaticFinalValues.RESULT_PICK_VIDEO);
                    for (VideoFile file : list) {
                        videoFileName = file.getPath();
                    }


                    //这一段用来判断视频时间的
                    try {
                        MediaPlayer player = new MediaPlayer();
                        player.setDataSource(videoFileName);
                        player.prepare();
                        int duration = player.getDuration();
                        player.release();
                        int s = duration / 1000;
                        int hour = s / 3600;
                        int minute = s % 3600 / 60;
                        int second = s % 60;
                        Log.e(TAG, "视频文件长度,分钟: " + minute + "视频有" + s + "秒");
                        if (s >= 120) {
                            Toast.makeText(this, "视频剪辑不能超过2分钟", Toast.LENGTH_LONG).show();
                            return;
                        } else if (s < 5) {
                            Toast.makeText(this, "视频剪辑不能少于5秒", Toast.LENGTH_LONG).show();
                            return;
                        } else {
                            Intent intent = new Intent(RecorderActivity.this, LocalVideoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString(StaticFinalValues.VIDEOFILEPATH, videoFileName);
                            bundle.putInt(StaticFinalValues.MISNOTCOMELOCAL, 0);
                            intent.putExtra(StaticFinalValues.BUNDLE, bundle);
                            startActivity(intent);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (mMyHandler != null) {
            mMyHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }
}
